/**
  ******************************************************************************
  * @file           : led485.c
  * @brief          : Variable-frequency bsp program
  ******************************************************************************
  * @attention
  *
  ******************************************************************************
  */
#include "bsp.h"

#define RS485_DIR_Pin           GPIO_PIN_12
#define RS485_DIR_GPIO_Port     GPIOD
#define RS485_DIR(x)            x?(GPIO_BOP(RS485_DIR_GPIO_Port) = (uint32_t)RS485_DIR_Pin):(GPIO_BC(RS485_DIR_GPIO_Port) = (uint32_t)RS485_DIR_Pin)

/* USART3 init function */
void RS485_2_BspInit(void)
{
	rcu_periph_clock_enable(RCU_GPIOB);
  rcu_periph_clock_enable(RCU_GPIOD);
	rcu_periph_clock_enable(RCU_USART2);
	
	gpio_mode_set(RS485_DIR_GPIO_Port, GPIO_MODE_OUTPUT, GPIO_PUPD_PULLUP, RS485_DIR_Pin);
	gpio_output_options_set(RS485_DIR_GPIO_Port, GPIO_OTYPE_PP, GPIO_OSPEED_25MHZ, RS485_DIR_Pin);
	
	gpio_af_set(GPIOB, GPIO_AF_7, GPIO_PIN_10);
	gpio_af_set(GPIOB, GPIO_AF_7, GPIO_PIN_11);
	
	/* configure USART2 Tx as alternate function push-pull */
	gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_10);
	gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_10);

	/* configure USART2 Rx as alternate function push-pull */
	gpio_mode_set(GPIOB, GPIO_MODE_AF, GPIO_PUPD_PULLUP, GPIO_PIN_11);
	gpio_output_options_set(GPIOB, GPIO_OTYPE_PP, GPIO_OSPEED_50MHZ, GPIO_PIN_11);
	
  
  /* USART configure */
	usart_deinit(USART2);
	usart_baudrate_set(USART2, 115200u);
	usart_word_length_set(USART2, USART_WL_8BIT);
	usart_parity_config(USART2, USART_PM_NONE);
	usart_stop_bit_set(USART2, USART_STB_1BIT);
	usart_receive_config(USART2, USART_RECEIVE_DISABLE);
	usart_transmit_config(USART2, USART_TRANSMIT_ENABLE);
	usart_halfduplex_disable(USART2);
	usart_synchronous_clock_disable(USART2);
	
	usart_receiver_timeout_disable(USART2);
	
	nvic_irq_disable(USART2_IRQn);
	usart_interrupt_disable(USART2, USART_INT_RBNE);
	usart_interrupt_disable(USART2, USART_INT_RT);
	
	usart_enable(USART2);
  
  RS485_DIR(1);
}

void RS485_2_UartSendBuf(const uint8_t *buf, uint32_t len)
{
	uint32_t i;
  
	RS485_DIR(1);
	
	for(i=0; i<len; i++)
	{
    USART_DATA(USART2) = (buf[i]& (uint16_t)0x01FFU);
    while(!(USART_STAT0(USART2) & USART_STAT0_TBE));
	}
	
	while (!(USART_STAT0(USART2) & USART_STAT0_TC));
}

/**
  * @brief This function handles USART3 global interrupt.
  */
void USART2_IRQHandler(void)
{
	if(usart_interrupt_flag_get(USART2, USART_INT_FLAG_RBNE) != RESET)
	{
    
	}
}
